package cn.zzp.system.service.impl;

import cn.zzp.basic.service.impl.BaseServiceImpl;
import cn.zzp.system.domain.Role;
import cn.zzp.system.mapper.RoleMapper;
import cn.zzp.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Administrator
 * @description:
 * @date 2022/8/2 19:25
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 添加
     * @param role
     */
    @Transactional
    @Override
    public void add(Role role) {
        roleMapper.add(role);

        insertRelationTable(role);
    }

    /**
     * 添加关联表
     * @param role
     */
    private void insertRelationTable(Role role) {
        // 赋予权限
        List<Long> permissions = role.getPermissions();
        if (permissions.size() > 0) {
            roleMapper.addRolePermission(role.getId(),permissions);
        }
        // 赋予菜单
        List<Long> menus = role.getMenus();
        if (menus.size() > 0){
            roleMapper.addRoleMenu(role.getId(),menus);
        }
    }

    /**
     * 删除
     * @param id
     */
    @Transactional
    @Override
    public void delete(Long id) {
        //删除t_role_permission中间表相关数据
        roleMapper.deleteRolePermissionByRoleId(id);
        // 删除t_role_menu中间表相关数据
        roleMapper.deleteRoleMenuByRoleId(id);
        // 删除t_employee_role中间表相关数据
        roleMapper.deleteEmployeeRoleByRoleId(id);

        roleMapper.delete(id);
    }

    @Transactional
    @Override
    public void update(Role role) {
        //更新角色
        roleMapper.update(role);
        // 先删除，再存入
        roleMapper.deleteRoleMenuByRoleId(role.getId());
        roleMapper.deleteRolePermissionByRoleId(role.getId());

        insertRelationTable(role);

    }
}
